<?php

namespace app\api\controller;

use app\api\model\Goods\Speci\Color;
use app\api\model\Goods\Speci\Size;
use app\api\model\Goods\Speci\Style;
use app\api\model\Goods\Speci\Unit;
use app\api\model\ProductStock;
use app\api\validate\GoodsValidate;
use think\exception\DbException;
use think\facade\Request;
use think\Db;

class Commodity extends Common
{
    /**
     * @param Request $request
     * @param \app\api\model\Commodity $commodity
     * @return \think\response\Json
     */
    public function index(Request $request, \app\api\model\Commodity $commodity)
    {
        $where = [];
        if ($request::has('name', 'param', true)) {
            $where[] = ['name', 'LIKE', '%' . $request::param('name') . '%'];
        }
        if ($request::has('status', 'param', true)) {
            $where[] = ['status', '=', $request::param('status')];
        }
        if ($request::has('brand', 'param', true)) {
            $where[] = ['brand', '=', $request::param('brand')];
        }
        if ($request::has('category', 'param', true)) {
            $where[] = ['category', '=', $request::param('category')];
        }
        return $this->returnJson(
            200,
            'ok',
            $commodity->index($where, $request::param('page'), $request::param('size'))
        );
    }

    /**
     * @param $id
     * @param $data
     * @param \app\api\model\Commodity $model
     * @param int $page
     * @param int $size
     * @return string
     */
    public function indexProduct($id, \app\api\model\Commodity $model)
    {
        try {
            return $this->returnJson(200, 'ok', $model::get($id)->products()->select());
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getProduct($id, \app\api\model\Commodity $model)
    {
        try {
            $list = model('product')->where('commodity_id', $id)->select()->toArray();
            $goods = Db::name('Commodity')->find($id);
            //$list =[];
            foreach ($list as $k => $v) {
                //$list =model('product')->where('color',$v['color'])->select()->toArray();
                $list[$k]['name'] = $goods['name'];
                $list[$k]['unit'] = Unit::find($goods['unit'])['name'];
                $list[$k]['goods_code'] = $goods['goods_code'];
                $list[$k]['item'] = $goods['item'];
                $list[$k]['purchase_price'] = $goods['purchase_price'];
                $list[$k]['trade_price'] = $goods['trade_price'];
                $list[$k]['stock'] = ProductStock::where('product_id', $v['id'])->find()['stock'];
            }
            return $this->returnJson(200, 'ok', $list);
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getGoods(Request $request, \app\api\model\Commodity $commodity)
    {
        $where = [];
        if ($request::has('brand', 'param', true)) {
            $where[] = ['brand', '=', $request::param('brand')];
        }
        if ($request::has('category', 'param', true)) {
            $where[] = ['category', '=', $request::param('category')];
        }
        if ($request::has('name', 'param', true)) {
            $where[] = ['name', 'like', '%' . $request::param('name') . '%'];
        }
        return $this->returnJson(200, 'ok', $commodity->getGoods($where));
    }

    /**
     * @param $id
     * @param \app\api\model\Commodity $commodity
     * @return \think\response\Json
     */
    public function show($id, \app\api\model\Commodity $commodity)
    {
        return $this->returnJson(200, 'ok', $commodity->info($id));
    }

    /**
     * @param Request $request
     * @param \app\api\model\Commodity $commodityModel
     * @return \think\response\Json
     */
    public function store(Request $request, \app\api\model\Commodity $commodityModel)
    {
        $data = $request::param();
        $validate = new GoodsValidate();
        if (!$validate->check($data)) {
            return $this->returnJson(500, $validate->getError());
        }
        Db::startTrans();
        // 新建 商品
        try {
            $commodity = $commodityModel->add($request::only($commodityModel->getField()['commodity']));
            $productField = $data['goods'];
            $productField['commodity_id'] = $commodity->id;
            // 新建 单品
            try {
                $product = $commodity->products()->addAll($productField);
                Db::commit();
                return $this->returnJson(200, 'ok', $commodityModel->info($commodity->id));
            } catch (\Exception $exception) {
                Db::rollback();
                return $this->returnJson(
                    500,
                    $exception->getMessage() . PHP_EOL
                    . 'in' . $exception->getFile()
                    . ':' . $exception->getLine()
                );
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->returnJson(
                500,
                $exception->getMessage() . PHP_EOL
                . 'in' . $exception->getFile()
                . ':' . $exception->getLine()
            );
        }
    }

    /**
     * @param $id
     * @param Request $request
     * @param \app\api\model\Commodity $commodityModel
     * @return \think\response\Json
     */
    public function update($id, Request $request, \app\api\model\Commodity $commodityModel)
    {
        $data = $request::param();
//        $data['detail'] = $data['desc'];
        $validate = new GoodsValidate();
        if (!$validate->check($data)) {
            return json(['code' => 500, 'msg' => $validate->getError()]);
        }
//        var_dump($data);
//        exit();
        Db::startTrans();
        // 新建 商品
        try {
            $commodity = $commodityModel->findOrFail($id);
            $res = $commodityModel->edit($id, $request::only($commodityModel->getField()['commodity']));
            $productField = $data['goods'];
            $productField['commodity_id'] = $commodity->id;
            // 新建 单品
            try {
                $product = $commodity->products()->addAll($productField);
                Db::commit();
                return $this->returnJson(200, 'ok', $commodity);
            } catch (\Exception $exception) {
                Db::rollback();
                return $this->returnJson(
                    500,
                    $exception->getMessage() . PHP_EOL
                    . 'in' . $exception->getFile()
                    . ':' . $exception->getLine()
                );
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->returnJson(
                500,
                $exception->getMessage() . PHP_EOL
                . 'in' . $exception->getFile()
                . ':' . $exception->getLine()
            );
        }
//        $res = $commodityModel->edit($id, $data);
//        return is_string($res) ? $this->returnJson(500, $res) : $this->returnJson(200, 'ok', $res);
    }

    /**
     * @param $id
     * @param Request $request
     * @param \app\api\model\Commodity $commodityModel
     * @return \think\response\Json
     */
    public function delete($id, Request $request, \app\api\model\Commodity $commodityModel)
    {
        $res = $commodityModel->del($id, $request::param('recursive', false));
        return is_string($res) ? $this->returnJson(500, $res) : $this->returnJson(200, 'ok', $res);
    }
}
